#include <stdlib.h>
#include <string.h>

#include "dynstring.h"

void dynstring_init(DynamicString* dynstring) {
    dynstring->capacity = 1;
    dynstring->data = malloc(sizeof(char) * dynstring->capacity);
    dynstring->data[0] = '\0';
    dynstring->size = 0;
}

void dynstring_free(DynamicString* dynstring) {
    free(dynstring->data);
    dynstring->data = NULL;
    dynstring->size = 0;
    dynstring->capacity = 0;
}

void dynstring_clear(DynamicString* dynstring) {
    dynstring->size = 0;
    dynstring->data[0] = '\0';
}

void dynstring_push_back(DynamicString* dynstring, const char* string) {
    size_t len = strlen(string);

    // if resize is needed
    int realloc = 0;
    while (dynstring->size + len >= dynstring->capacity) {
        dynstring->capacity *= 2;
        realloc = 1;
    }

    if (realloc) {
        char* newalloc = (char*) malloc(sizeof(char) * dynstring->capacity);
        memcpy(newalloc, dynstring->data, dynstring->size * sizeof(char));
        free(dynstring->data);
        dynstring->data = newalloc;
    }

    memcpy(dynstring->data + dynstring->size, string, len);
    dynstring->size += len;
    dynstring->data[dynstring->size] = '\0';
}